<template>
  <div class="user-role-permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理中心</span>
        </div>
      </template>
      
      <!-- TAB 切换 -->
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <!-- 用户管理 TAB -->
        <el-tab-pane label="用户管理" name="users">
          <div class="tab-content">
            <!-- 搜索和筛选 -->
            <div class="search-bar">
              <el-form :inline="true" :model="userSearchForm" class="search-form">
                <el-form-item label="用户名">
                  <el-input
                    v-model="userSearchForm.search"
                    placeholder="请输入用户名"
                    clearable
                    @keyup.enter="handleUserSearch"
                  />
                </el-form-item>
                
                <el-form-item label="角色">
                  <el-select v-model="userSearchForm.role" placeholder="所有" clearable>
                    <el-option label="所有" value="" />
                    <el-option
                      v-for="role in roleStore.roles"
                      :key="role.code"
                      :label="role.name"
                      :value="role.code"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleUserSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetUserSearch">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <!-- 用户表格 -->
            <el-table
              v-loading="userStore.loading"
              :data="userStore.users"
              style="width: 100%"
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="roles" label="角色">
                <template #default="{ row }">
                  <div class="role-tags">
                    <el-tag
                      v-for="role in row.roles"
                      :key="role.id"
                      :type="getRoleTagType(role.code)"
                      class="role-tag"
                    >
                      {{ role.name }}
                    </el-tag>
                    <el-tag v-if="!row.roles || row.roles.length === 0" type="info">
                      无角色
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                    {{ row.status === 'active' ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="updatedAt" label="修改时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.updatedAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    @click="showEditUserDialog(row)"
                    v-permission="'user:update'"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDeleteUser(row)"
                    v-permission="'user:delete'"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 用户分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="userCurrentPage"
                v-model:page-size="userPageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="userStore.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleUserSizeChange"
                @current-change="handleUserCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 角色管理 TAB -->
        <el-tab-pane label="角色管理" name="roles">
          <div class="tab-content">
            <!-- 搜索和筛选 -->
            <div class="search-bar">
              <el-form :inline="true" :model="roleSearchForm" class="search-form">
                <el-form-item label="角色名称">
                  <el-input
                    v-model="roleSearchForm.search"
                    placeholder="请输入角色名称"
                    clearable
                    @keyup.enter="handleRoleSearch"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleRoleSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetRoleSearch">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <!-- 角色表格 -->
            <el-table
              v-loading="roleStore.loading"
              :data="roleStore.roles"
              style="width: 100%"
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="code" label="角色代码" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="is_active" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.is_active ? 'success' : 'danger'">
                    {{ row.is_active ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="300">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    @click="showEditRoleDialog(row)"
                    v-permission="'role:update'"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    @click="showPermissionDialog(row)"
                    v-permission="'role:update'"
                  >
                    权限
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDeleteRole(row)"
                    v-permission="'role:delete'"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 角色分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="roleCurrentPage"
                v-model:page-size="rolePageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="roleStore.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleRoleSizeChange"
                @current-change="handleRoleCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 权限管理 TAB -->
        <el-tab-pane label="权限管理" name="permissions">
          <div class="tab-content">
            <!-- 搜索和筛选 -->
            <div class="search-bar">
              <el-form :inline="true" :model="permissionSearchForm" class="search-form">
                <el-form-item label="权限名称">
                  <el-input
                    v-model="permissionSearchForm.search"
                    placeholder="请输入权限名称"
                    clearable
                    @keyup.enter="handlePermissionSearch"
                  />
                </el-form-item>
                
                <el-form-item label="资源">
                  <el-select v-model="permissionSearchForm.resource" placeholder="请选择资源" clearable>
                    <el-option label="所有" value="" />
                    <el-option
                      v-for="resource in permissionStore.resources"
                      :key="resource"
                      :label="resource"
                      :value="resource"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handlePermissionSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="resetPermissionSearch">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <!-- 权限表格 -->
            <el-table
              v-loading="permissionStore.loading"
              :data="permissionStore.permissions"
              style="width: 100%"
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="权限名称" />
              <el-table-column prop="code" label="权限代码" />
              <el-table-column prop="resource" label="资源">
                <template #default="{ row }">
                  <el-tag type="info">{{ row.resource }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="action" label="操作">
                <template #default="{ row }">
                  <el-tag type="success">{{ row.action }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="created_at" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    @click="showEditPermissionDialog(row)"
                    v-permission="'permission:update'"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDeletePermission(row)"
                    v-permission="'permission:delete'"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 权限分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="permissionCurrentPage"
                v-model:page-size="permissionPageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="permissionStore.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePermissionSizeChange"
                @current-change="handlePermissionCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isUserEdit ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item v-if="!isUserEdit" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="role_ids">
          <el-select
            v-model="userForm.role_ids"
            placeholder="请选择角色"
            multiple
            clearable
          >
            <el-option
              v-for="role in roleStore.roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveUser">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isRoleEdit ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色代码" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="is_active">
          <el-select v-model="roleForm.is_active" placeholder="请选择状态">
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRole">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      :title="isPermissionEdit ? '编辑权限' : '添加权限'"
      width="600px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限代码" />
        </el-form-item>
        
        <el-form-item label="资源" prop="resource">
          <el-select v-model="permissionForm.resource" placeholder="请选择资源" clearable>
            <el-option
              v-for="resource in permissionStore.resources"
              :key="resource"
              :label="resource"
              :value="resource"
            />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="permissionForm.resource === 'custom'" label="自定义资源" prop="customResource">
          <el-input v-model="permissionForm.customResource" placeholder="请输入自定义资源名称" />
        </el-form-item>
        
        <el-form-item label="操作" prop="action">
          <el-select v-model="permissionForm.action" placeholder="请选择操作" clearable>
            <el-option
              v-for="action in permissionStore.actions"
              :key="action"
              :label="action"
              :value="action"
            />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="permissionForm.action === 'custom'" label="自定义操作" prop="customAction">
          <el-input v-model="permissionForm.customAction" placeholder="请输入自定义操作名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermission">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="assignPermissionDialogVisible"
      title="权限分配"
      width="600px"
    >
      <div class="permission-dialog">
        <div class="role-info">
          <h4>角色：{{ currentRole?.name }}</h4>
          <p>代码：{{ currentRole?.code }}</p>
        </div>
        
        <div class="permission-content">
          <div class="permission-header">
            <span>可用权限</span>
            <div class="permission-actions">
              <el-button @click="selectAllPermissions">全选</el-button>
              <el-button @click="clearAllPermissions">清空</el-button>
            </div>
          </div>
          
          <div class="permission-list">
            <el-checkbox-group v-model="selectedPermissions">
              <div v-for="permission in permissionStore.permissions" :key="permission.id" class="permission-item">
                <el-checkbox :label="permission.id">
                  <div class="permission-info">
                    <span class="permission-name">{{ permission.name }}</span>
                    <span class="permission-code">{{ permission.code }}</span>
                    <span class="permission-resource">{{ permission.resource }}:{{ permission.action }}</span>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignPermissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 权限角色对话框 -->
    <el-dialog
      v-model="permissionRoleDialogVisible"
      title="权限角色"
      width="600px"
    >
      <div class="role-dialog">
        <div class="permission-info">
          <h4>权限：{{ currentPermission?.name }}</h4>
          <p>代码：{{ currentPermission?.code }}</p>
          <p>资源：{{ currentPermission?.resource }}:{{ currentPermission?.action }}</p>
        </div>
        
        <div class="role-content">
          <div class="role-header">
            <span>拥有此权限的角色</span>
          </div>
          
          <div class="role-list">
            <el-table
              v-loading="roleStore.loading"
              :data="permissionRoles"
              style="width: 100%"
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="code" label="角色代码" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="is_active" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.is_active ? 'success' : 'danger'">
                    {{ row.is_active ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionRoleDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRoleStore } from '@/stores/role'
import { usePermissionStore } from '@/stores/permission'
import type { User, CreateUserForm, UpdateUserForm } from '@/stores/user'
import type { Role, CreateRoleForm, UpdateRoleForm } from '@/stores/role'
import type { Permission, CreatePermissionForm, UpdatePermissionForm } from '@/stores/permission'

const userStore = useUserStore()
const roleStore = useRoleStore()
const permissionStore = usePermissionStore()

// TAB 控制
const activeTab = ref('users')

// 用户相关
const userSearchForm = reactive({
  search: '',
  role: ''
})
const userCurrentPage = ref(1)
const userPageSize = ref(10)
const userDialogVisible = ref(false)
const isUserEdit = ref(false)
const userFormRef = ref<FormInstance>()
const userForm = reactive({
  id: 0,
  username: '',
  email: '',
  password: '',
  role: 'user',
  status: 'active',
  role_ids: [] as number[]
})

// 角色相关
const roleSearchForm = reactive({
  search: ''
})
const roleCurrentPage = ref(1)
const rolePageSize = ref(10)
const roleDialogVisible = ref(false)
const isRoleEdit = ref(false)
const roleFormRef = ref<FormInstance>()
const roleForm = reactive({
  id: 0,
  name: '',
  code: '',
  description: '',
  is_active: true
})

// 权限相关
const permissionSearchForm = reactive({
  search: '',
  resource: ''
})
const permissionCurrentPage = ref(1)
const permissionPageSize = ref(10)
const permissionDialogVisible = ref(false)
const isPermissionEdit = ref(false)
const permissionFormRef = ref<FormInstance>()
const permissionForm = reactive({
  id: 0,
  name: '',
  code: '',
  resource: '',
  customResource: '',
  action: '',
  customAction: '',
  description: ''
})

// 权限分配相关
const assignPermissionDialogVisible = ref(false)
const currentRole = ref<Role | null>(null)
const selectedPermissions = ref<number[]>([])

// 权限角色相关
const permissionRoleDialogVisible = ref(false)
const currentPermission = ref<Permission | null>(null)
const permissionRoles = ref<any[]>([])

// 计算最终的资源和操作值
const finalResource = computed(() => {
  return permissionForm.resource === 'custom' ? permissionForm.customResource : permissionForm.resource
})

const finalAction = computed(() => {
  return permissionForm.action === 'custom' ? permissionForm.customAction : permissionForm.action
})

// 表单验证规则
const userRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const roleRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { min: 2, max: 50, message: '角色代码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  is_active: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const permissionRules: FormRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 100, message: '权限名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { min: 2, max: 100, message: '权限代码长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  resource: [
    { required: true, message: '请选择资源', trigger: 'change' }
  ],
  customResource: [
    { required: true, message: '请输入自定义资源名称', trigger: 'blur' }
  ],
  action: [
    { required: true, message: '请选择操作', trigger: 'change' }
  ],
  customAction: [
    { required: true, message: '请输入自定义操作名称', trigger: 'blur' }
  ]
}

// 初始化
onMounted(async () => {
  await loadUsers()
  await loadRoles()
  await loadPermissions()
  await loadResources()
  await loadActions()
})

// TAB 切换处理
const handleTabClick = (tab: any) => {
  // 根据不同的 TAB 加载相应的数据
  switch (tab.props.name) {
    case 'users':
      loadUsers()
      break
    case 'roles':
      loadRoles()
      break
    case 'permissions':
      loadPermissions()
      break
  }
}

// 用户相关方法
const loadUsers = async () => {
  await userStore.fetchUsers({
    page: userCurrentPage.value,
    pageSize: userPageSize.value,
    search: userSearchForm.search,
    role: userSearchForm.role
  })
}

const handleUserSearch = () => {
  userCurrentPage.value = 1
  loadUsers()
}

const resetUserSearch = () => {
  userSearchForm.search = ''
  userSearchForm.role = ''
  userCurrentPage.value = 1
  loadUsers()
}

const handleUserSizeChange = (val: number) => {
  userPageSize.value = val
  loadUsers()
}

const handleUserCurrentChange = (val: number) => {
  userCurrentPage.value = val
  loadUsers()
}

const showAddUserDialog = () => {
  isUserEdit.value = false
  resetUserForm()
  userDialogVisible.value = true
}

const showEditUserDialog = (user: User) => {
  isUserEdit.value = true
  Object.assign(userForm, {
    ...user,
    role_ids: user.roles?.map(role => role.id) || []
  })
  userDialogVisible.value = true
}

const resetUserForm = () => {
  Object.assign(userForm, {
    id: 0,
    username: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active',
    role_ids: []
  })
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }
}

const handleSaveUser = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isUserEdit.value) {
          const updateData: UpdateUserForm = {
            id: userForm.id,
            username: userForm.username,
            email: userForm.email,
            role: userForm.role,
            status: userForm.status as 'active' | 'inactive',
            role_ids: userForm.role_ids
          }
          await userStore.updateUser(updateData)
          ElMessage.success('用户更新成功')
        } else {
          const createData: CreateUserForm = {
            username: userForm.username,
            email: userForm.email,
            password: userForm.password,
            role: userForm.role
          }
          await userStore.createUser(createData)
          ElMessage.success('用户添加成功')
        }
        
        userDialogVisible.value = false
        loadUsers()
      } catch (error: any) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

const handleDeleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 角色相关方法
const loadRoles = async () => {
  await roleStore.fetchRoles({
    page: roleCurrentPage.value,
    pageSize: rolePageSize.value,
    search: roleSearchForm.search
  })
}

const handleRoleSearch = () => {
  roleCurrentPage.value = 1
  loadRoles()
}

const resetRoleSearch = () => {
  roleSearchForm.search = ''
  roleCurrentPage.value = 1
  loadRoles()
}

const handleRoleSizeChange = (val: number) => {
  rolePageSize.value = val
  loadRoles()
}

const handleRoleCurrentChange = (val: number) => {
  roleCurrentPage.value = val
  loadRoles()
}

const showAddRoleDialog = () => {
  isRoleEdit.value = false
  resetRoleForm()
  roleDialogVisible.value = true
}

const showEditRoleDialog = (role: Role) => {
  isRoleEdit.value = true
  Object.assign(roleForm, role)
  roleDialogVisible.value = true
}

const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: 0,
    name: '',
    code: '',
    description: '',
    is_active: true
  })
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
}

const handleSaveRole = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isRoleEdit.value) {
          const updateData: UpdateRoleForm = {
            id: roleForm.id,
            name: roleForm.name,
            code: roleForm.code,
            description: roleForm.description,
            is_active: roleForm.is_active
          }
          await roleStore.updateRole(updateData)
          ElMessage.success('角色更新成功')
        } else {
          const createData: CreateRoleForm = {
            name: roleForm.name,
            code: roleForm.code,
            description: roleForm.description,
            is_active: roleForm.is_active
          }
          await roleStore.createRole(createData)
          ElMessage.success('角色添加成功')
        }
        
        roleDialogVisible.value = false
        loadRoles()
      } catch (error: any) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

const handleDeleteRole = async (role: Role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await roleStore.deleteRole(role.id)
    ElMessage.success('角色删除成功')
    loadRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const showPermissionDialog = async (role: Role) => {
  currentRole.value = role
  assignPermissionDialogVisible.value = true
  
  const result = await roleStore.getRolePermissions(role.id)
  if (result.success) {
    selectedPermissions.value = result.permissions.map((p: any) => p.id)
  }
}

const selectAllPermissions = () => {
  selectedPermissions.value = permissionStore.permissions.map(p => p.id)
}

const clearAllPermissions = () => {
  selectedPermissions.value = []
}

const handleSavePermissions = async () => {
  if (!currentRole.value) return
  
  try {
    await roleStore.assignRolePermissions(
      currentRole.value.id,
      selectedPermissions.value
    )
    ElMessage.success('权限分配成功')
    assignPermissionDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '权限分配失败')
  }
}

// 权限相关方法
const loadPermissions = async () => {
  await permissionStore.fetchPermissions({
    page: permissionCurrentPage.value,
    pageSize: permissionPageSize.value,
    search: permissionSearchForm.search,
    resource: permissionSearchForm.resource
  })
}

const loadResources = async () => {
  await permissionStore.fetchResources()
}

const loadActions = async () => {
  await permissionStore.fetchActions()
}

const handlePermissionSearch = () => {
  permissionCurrentPage.value = 1
  loadPermissions()
}

const resetPermissionSearch = () => {
  permissionSearchForm.search = ''
  permissionSearchForm.resource = ''
  permissionCurrentPage.value = 1
  loadPermissions()
}

const handlePermissionSizeChange = (val: number) => {
  permissionPageSize.value = val
  loadPermissions()
}

const handlePermissionCurrentChange = (val: number) => {
  permissionCurrentPage.value = val
  loadPermissions()
}

const showAddPermissionDialog = () => {
  isPermissionEdit.value = false
  resetPermissionForm()
  permissionDialogVisible.value = true
}

const showEditPermissionDialog = (permission: Permission) => {
  isPermissionEdit.value = true
  Object.assign(permissionForm, permission)
  permissionDialogVisible.value = true
}

const resetPermissionForm = () => {
  Object.assign(permissionForm, {
    id: 0,
    name: '',
    code: '',
    resource: '',
    customResource: '',
    action: '',
    customAction: '',
    description: ''
  })
  if (permissionFormRef.value) {
    permissionFormRef.value.clearValidate()
  }
}

const handleSavePermission = async () => {
  if (!permissionFormRef.value) return
  
  await permissionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isPermissionEdit.value) {
          const updateData: UpdatePermissionForm = {
            id: permissionForm.id,
            name: permissionForm.name,
            code: permissionForm.code,
            resource: finalResource.value,
            action: finalAction.value,
            description: permissionForm.description
          }
          await permissionStore.updatePermission(updateData)
          ElMessage.success('权限更新成功')
        } else {
          const createData: CreatePermissionForm = {
            name: permissionForm.name,
            code: permissionForm.code,
            resource: finalResource.value,
            action: finalAction.value,
            description: permissionForm.description
          }
          await permissionStore.createPermission(createData)
          ElMessage.success('权限添加成功')
        }
        
        permissionDialogVisible.value = false
        loadPermissions()
        loadResources()
        loadActions()
      } catch (error: any) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

const handleDeletePermission = async (permission: Permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${permission.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await permissionStore.deletePermission(permission.id)
    ElMessage.success('权限删除成功')
    loadPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const showRoleDialog = async (permission: Permission) => {
  currentPermission.value = permission
  permissionRoleDialogVisible.value = true
  
  const result = await permissionStore.getPermissionRoles(permission.id)
  if (result.success) {
    permissionRoles.value = result.roles
  }
}

// 工具方法
const getRoleTagType = (role: string) => {
  switch (role) {
    case 'admin':
      return 'danger'
    case 'user':
      return 'primary'
    case 'guest':
      return 'info'
    default:
      return 'info'
  }
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}
</script>

<style scoped>
.user-role-permission-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tab-content {
  margin-top: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.role-tag {
  margin-right: 4px;
}

.permission-dialog {
  .role-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    h4 {
      margin: 0 0 5px 0;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
    }
  }
  
  .permission-content {
    .permission-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      font-weight: bold;
    }
    
    .permission-list {
      max-height: 400px;
      overflow-y: auto;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 10px;
      
      .permission-item {
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .permission-info {
          display: flex;
          flex-direction: column;
          margin-left: 10px;
          
          .permission-name {
            font-weight: bold;
            color: #303133;
          }
          
          .permission-code {
            color: #909399;
            font-size: 12px;
          }
          
          .permission-resource {
            color: #409eff;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.role-dialog {
  .permission-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    h4 {
      margin: 0 0 5px 0;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
    }
  }
  
  .role-content {
    .role-header {
      margin-bottom: 15px;
      font-weight: bold;
    }
    
    .role-list {
      max-height: 400px;
      overflow-y: auto;
    }
  }
}
</style>
